package com.olap.starter.core.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.olap.starter.core.base.QueryGenerator;
import com.olap.starter.core.response.Result;
import com.olap.starter.core.response.ResultUtil;
import com.olap.starter.core.response.paging.PageRequest;
import com.olap.starter.core.response.paging.TablePageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author WBG
 * @date 2022/8/30 22:03
 * @describe
 */

public class BaseController<T, S extends BaseService> extends ResultUtil {
    private static final Logger log = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    S service;

    public BaseController() {
    }

    @GetMapping({"/list"})
    public TablePageResponse queryPageList(T param) {
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(param);
        IPage page = this.service.page(PageRequest.doIPage(),queryWrapper);
        return respTablePageResponse(page);
    }

    @GetMapping({"/listAll"})
    public Result queryPageList() {
        return success(this.service.list());
    }

    @PostMapping({"/save"})
    public Result<?> save(@RequestBody T param) {
        this.service.save(param);
        return success(param, "添加成功！");
    }

    @PutMapping({"/edit"})
    public Result<?> edit(@RequestBody T param) {
        this.service.updateById(param);
        return success("编辑成功!");
    }

    @DeleteMapping({"/delete"})
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        this.service.removeById(id);
        return success("删除成功!");
    }

    @DeleteMapping({"/deleteBatch"})
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.service.removeByIds(Arrays.asList(ids.split(",")));
        return success("批量删除成功!");
    }

    @GetMapping({"/queryById"})
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        T entity = (T) this.service.getById(id);
        return entity == null ? error("未找到对应数据") : success(entity);
    }

    @GetMapping({"/count"})
    public Result<?> count(T param) {
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(param);
        return success(this.service.count(queryWrapper));
    }

    @GetMapping({"/getOne"})
    public Result<?> getOne(T param) {
        QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(param);
        return success(this.service.getOne(queryWrapper));
    }

    public S getService() {
        return service;
    }

}
